/**
 * Created by Eoly on 2017/2/16.
 * Call http://palerock.cn
 */
var orderPage = angular.module('orderPage', ['ngRoute']);

//自定义过滤器——转换订单状态为文字
orderPage.filter('explainOrderStatus', function () {
    return function (status) {
        var result = '';
        switch (status) {
            case -1:
                result = '已失效';
                break;
            case 0:
                result = '未付款';
                break;
            case 1:
                result = '付款成功，等待拼团';
                break;
            case 2:
                result = '拼团成功，等待发货';
                break;
            case 3:
                result = '已发货';
                break;
            case 4:
                result = '交易成功';
                break;
            default:
                result = '未知状态';
        }
        //input 就是我们要处理的数据
        return result;
    }
});

orderPage.filter('explainTime', function () {
    return function (time) {
        return app.explainTime(time);
    };
});

/**
 * 用户订单
 */
orderPage.controller('order', function ($scope, $http) {

    // 默认查询用户订单
    $scope.orderSelect = '0';

    $scope.suiMobileInit = function (isNotChangeContent) {
        app.suiInit(isNotChangeContent);
        $scope.groupId = sessionStorage.getItem('ptsc_order_group_id');
        if ($scope.groupId != null) {
            $scope.orderSelect = '2';
            sessionStorage.removeItem('ptsc_order_group_id');
        }
    };

    //声明从缓存获取的团对象
    $scope.preOrder = null;

    //声明从服务器获取的订单列表
    $scope.orderList = [];


    //获取订单列表
    $scope.getOrderList = function () {

        var url = null;
        console.log($scope.orderSelect);
        switch ($scope.orderSelect) {
            case '0':
                url = '/user/order/show-user-orders';
                break;
            case '1':
                url = '/user/order/show-seller-orders';
                break;
            case '2':
                url = '/user/order/show-group-orders';
                var param = {};
                param.groupId = $scope.groupId;
                break;
            default:
        }

        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        $scope.orderList = [];

        $http({
            method: 'get',
            url: net + url,
            params: param,
            headers: {'Authorization': 'Bearer ' + token}
        }).then(
            function (res) {
                $scope.error = res.data.error;
                if (!res.data.error) {

                    console.log(res);
                    $scope.orderList = res.data.dataList;

                } else {
                    if (res.data.error = 761) {
                        return;
                    }
                    $.alert("错误代码:" + res.data.error + "," + res.data.mes)
                }


            },
            //获取失败
            function (res) {
                $.alert('网络或设置错误');
            }
        )
    };

    //跳转到支付页面
    $scope.turnPay = function (order) {
        sessionStorage.setItem('ptsc_pre_order', JSON.stringify(order));
        app.turnHref('user-order.html', '#all', '#pay');
    };

    //跳转到详情页面
    $scope.turnDetail = function (order) {
        sessionStorage.setItem('ptsc_pre_order', JSON.stringify(order));
        app.turnHref('user-order.html', '#all', '#detail');
    };

    // 选择跳转页面
    $scope.autoTurn = function (order) {
        if (order.orderStatus == 0) {
            $scope.turnPay(order);
        } else {
            $scope.turnDetail(order);
        }
    };


    //声明从缓存获取的订单对象
    $scope.preOrder = null;

    //声明从服务器获取的订单对象
    $scope.orderDeeply = {};

    //获取在列表页储存的团id
    $scope.getSavePreOrder = function () {
        var order = sessionStorage.getItem("ptsc_pre_order");
        if (!order) {
            return;
        }
        $scope.preOrder = JSON.parse(order);
    };

    //获取订单详情
    $scope.getOrderDeeply = function () {

        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        $scope.getSavePreOrder();
        if (!$scope.preOrder) {
            $.alert('在上一步操作未指定具体订单', function () {
                app.backLastPosition();
            });
            return;
        }

        //指定请求参数
        var param = {};
        param.orderId = $scope.preOrder.orderId;

        $http({
            method: 'get',
            params: param,
            url: net + "/user/order/find-order-deeply",
            headers: {'Authorization': 'Bearer ' + token}
        }).then(
            function (res) {

                $scope.orderDtailError = res.data.error;

                if (!res.data.error || res.data.error == 1) {

                    console.log(res);
                    $scope.orderDeeply = res.data.data;
                    var src = eval(res.data.data.group.groupImgs);
                    $scope.orderDeeply.src = net + '/resources/img/' + src[0];
                    if($scope.orderDeeply.group.groupAliveHours!=-1)
                        $scope.leftTime = $scope.orderDeeply.group.groupInitTime + $scope.orderDeeply.group.groupAliveHours * 3600000 - new Date().getTime();
                    // console.log($scope.leftTime);
                    (function () {
                        window.setInterval(function () {
                            $scope.leftTime -= 1000;
                            $scope.$digest();
                        },1000);
                    })();

                } else {
                    $.alert("错误代码:" + res.data.error + "," + res.data.mes)
                }

            },
            //获取失败
            function (res) {
                $.alert('网络或设置错误');
            }
        )
    };


    //订单支付
    $scope.pay = function () {

        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        if (!$scope.orderDeeply.orderId) {
            $.alert('没有获得订单的具体信息，请重试');
            $scope.getOrderDeeply();
            return;
        }

        //声明参数
        var param = {};
        param.orderId = $scope.orderDeeply.orderId;
        app.openAndScanPsw("请输入支付密码：", function (psw) {
            param.payPsw = psw;
            if (param.payPsw == null) {
                return;
            }
            $http(
                {
                    method: 'post',
                    params: param,
                    url: net + "/user/order/pay",
                    headers: {'Authorization': 'Bearer ' + token}
                }
            ).then(
                function (res) {

                    if (!res.data.error) {

                        $.alert(res.data.mes, function () {
                            location.href = '#detail';
                        });
                        console.log(res);

                    } else {
                        $.alert("错误代码:" + res.data.error + "," + res.data.mes)
                    }

                },
                //获取失败
                function (res) {
                    $.alert('网络或设置错误');
                },
                //获取中
                function (res) {
                    console.log(res);
                }
            )
        });
    };

    // 改变筛选状态
    $scope.changeFilterStatus = function () {
        var option = [
            {
                name: '用户订单',
                value: 0
            },
            {
                name: '商家订单',
                value: 1
            }
        ];
        app.filterOptionsAction('选择需要查询的订单：', option, $scope.orderSelect, function (sel) {
            $scope.orderSelect = sel;
            // console.log(sel);
            $scope.getOrderList();
        })
    };

    // 跳转到团详情
    $scope.turnGroupDetail = function () {
        sessionStorage.setItem('ptsc_detail_groupId', $scope.orderDeeply.group.groupId);
        app.turnHref('user-order.html', '#detail', 'group-detail.html');
    };


    $scope.sentOut = function () {

        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }
        $.showIndicator();
        $http({
            method:'post',
            url:net+'/user/order/order-sent-out',
            headers: {'Authorization': 'Bearer ' + token},
            params:{orderId:$scope.orderDeeply.orderId}
        }).then(function (res) {
            $.hideIndicator();
            if (!res.data.error) {

                $.alert(res.data.mes,function () {
                    $scope.getOrderDeeply();
                });

            } else {
                $.alert("错误代码:" + res.data.error + "," + res.data.mes)
            }
        },function () {
            $.hideIndicator();
            $.alert('网络或设置错误');
        })
    };

    $scope.received = function () {

        //获取登录信息
        var token = app.getUserToken();

        if (!token) {
            return;
        }

        $.showIndicator();
        $http({
            method:'post',
            url:net+'/user/order/order-received',
            headers: {'Authorization': 'Bearer ' + token},
            params:{orderId:$scope.orderDeeply.orderId}
        }).then(function (res) {
            $.hideIndicator();
            if (!res.data.error) {

                $.alert(res.data.mes,function () {
                    $scope.getOrderDeeply();
                });

            } else {
                $.alert("错误代码:" + res.data.error + "," + res.data.mes)
            }
        },function () {
            $.hideIndicator();
            $.alert('网络或设置错误');
        })
    };

});

/**
 * 路由
 */
orderPage.config(function ($routeProvider) {
    $routeProvider.when('/all', {
        templateUrl: 'html/order-all-content.html',
        controller: 'order'
    }).when('/detail', {
        templateUrl: 'html/order-detail-content.html',
        controller: 'order'
    }).when('/pay', {
        templateUrl: 'html/order-pay-content.html',
        controller: 'order'
    }).otherwise({
        redirectTo: '/all'
    });
});